package cn.hh.ymcc.token;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign拦截器
 * 拦截器的目的是从请求头中拿到客户端传过来的Token,添加到Feign的请求头中
 */
public class FeignCarryTokenInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        //1.获取请求对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //2.从请求头获取到令牌
        String token = request.getHeader("Authorization");

        //3.把令牌添加到Fiegn的请求头
        if (StringUtils.hasLength(token)) { // 有的微服务不需要Token
            requestTemplate.header("Authorization", token);
        }
    }

}
